'use client'

import React from 'react'
import { Modal, Button, Alert } from 'antd'
import {
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    InfoCircleOutlined,
    WarningOutlined,
    DeleteOutlined,
    SaveOutlined,
    ExportOutlined
} from '@ant-design/icons'
import { useUIStore } from '@/stores/uiStore'

// 确认对话框类型
export type ConfirmationType = 'delete' | 'save' | 'export' | 'reset' | 'cancel' | 'warning' | 'info'

// 确认对话框配置
interface ConfirmationConfig {
    type: ConfirmationType
    title: string
    content: string | React.ReactNode
    okText?: string
    cancelText?: string
    okType?: 'primary' | 'danger' | 'default'
    icon?: React.ReactNode
    width?: number
    maskClosable?: boolean
    keyboard?: boolean
    centered?: boolean
    onOk?: () => void | Promise<void>
    onCancel?: () => void
}

// 预定义的确认对话框配置
const getConfirmationConfig = (type: ConfirmationType): Partial<ConfirmationConfig> => {
    switch (type) {
        case 'delete':
            return {
                title: '确认删除',
                okText: '删除',
                cancelText: '取消',
                okType: 'danger',
                icon: <DeleteOutlined className="text-red-500" />,
                content: '此操作不可撤销，确定要删除吗？'
            }
        case 'save':
            return {
                title: '保存确认',
                okText: '保存',
                cancelText: '取消',
                okType: 'primary',
                icon: <SaveOutlined className="text-blue-500" />,
                content: '确定要保存当前更改吗？'
            }
        case 'export':
            return {
                title: '导出确认',
                okText: '导出',
                cancelText: '取消',
                okType: 'primary',
                icon: <ExportOutlined className="text-green-500" />,
                content: '确定要导出数据吗？'
            }
        case 'reset':
            return {
                title: '重置确认',
                okText: '重置',
                cancelText: '取消',
                okType: 'danger',
                icon: <ExclamationCircleOutlined className="text-orange-500" />,
                content: '重置将清除所有当前设置，确定要继续吗？'
            }
        case 'cancel':
            return {
                title: '取消确认',
                okText: '确定取消',
                cancelText: '继续操作',
                okType: 'default',
                icon: <QuestionCircleOutlined className="text-gray-500" />,
                content: '确定要取消当前操作吗？未保存的更改将丢失。'
            }
        case 'warning':
            return {
                title: '警告',
                okText: '我知道了',
                cancelText: '取消',
                okType: 'primary',
                icon: <WarningOutlined className="text-yellow-500" />,
                content: '请注意相关风险后再继续操作。'
            }
        case 'info':
            return {
                title: '信息',
                okText: '确定',
                cancelText: '取消',
                okType: 'primary',
                icon: <InfoCircleOutlined className="text-blue-500" />,
                content: '请确认以下信息无误。'
            }
        default:
            return {
                title: '确认',
                okText: '确定',
                cancelText: '取消',
                okType: 'primary',
                icon: <QuestionCircleOutlined className="text-gray-500" />
            }
    }
}

// 确认对话框组件
interface ConfirmationDialogProps extends ConfirmationConfig {
    visible: boolean
    loading?: boolean
    onClose: () => void
}

export const ConfirmationDialog: React.FC<ConfirmationDialogProps> = ({
    visible,
    loading = false,
    onClose,
    ...config
}) => {
    const defaultConfig = getConfirmationConfig(config.type)
    const finalConfig = { ...defaultConfig, ...config }

    const handleOk = async () => {
        if (finalConfig.onOk) {
            try {
                await finalConfig.onOk()
                onClose()
            } catch (error) {
                console.error('Confirmation action failed:', error)
            }
        } else {
            onClose()
        }
    }

    const handleCancel = () => {
        if (finalConfig.onCancel) {
            finalConfig.onCancel()
        }
        onClose()
    }

    return (
        <Modal
            title={
                <div className="flex items-center space-x-2">
                    {finalConfig.icon}
                    <span>{finalConfig.title}</span>
                </div>
            }
            open={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={finalConfig.okText}
            cancelText={finalConfig.cancelText}
            okType={finalConfig.okType}
            confirmLoading={loading}
            width={finalConfig.width || 400}
            maskClosable={finalConfig.maskClosable !== false}
            keyboard={finalConfig.keyboard !== false}
            centered={finalConfig.centered !== false}
            destroyOnClose
        >
            <div className="py-4">
                {typeof finalConfig.content === 'string' ? (
                    <p className="text-gray-700">{finalConfig.content}</p>
                ) : (
                    finalConfig.content
                )}
            </div>
        </Modal>
    )
}

// 确认对话框管理器
export const ConfirmationManager: React.FC = () => {
    const { modals, closeModal } = useUIStore()

    return (
        <>
            {Object.entries(modals).map(([key, modal]) => {
                if (!modal.isOpen || modal.type !== 'confirmation') {
                    return null
                }

                const config = modal.data as unknown as ConfirmationConfig
                return (
                    <ConfirmationDialog
                        key={key}
                        visible={modal.isOpen}
                        onClose={() => closeModal(key)}
                        {...config}
                    />
                )
            })}
        </>
    )
}

// 确认对话框Hook
export const useConfirmation = () => {
    const { openModal, closeModal } = useUIStore()

    const showConfirmation = (config: ConfirmationConfig): Promise<boolean> => {
        return new Promise((resolve) => {
            const modalKey = `confirmation_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`

            const enhancedConfig = {
                ...config,
                onOk: async () => {
                    if (config.onOk) {
                        await config.onOk()
                    }
                    closeModal(modalKey)
                    resolve(true)
                },
                onCancel: () => {
                    if (config.onCancel) {
                        config.onCancel()
                    }
                    closeModal(modalKey)
                    resolve(false)
                }
            }

            openModal('confirmation', enhancedConfig)
        })
    }

    // 便捷方法
    const confirmDelete = (
        content?: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'delete',
            title: '确认删除',
            content: content || '此操作不可撤销，确定要删除吗？',
            onOk: onConfirm
        })
    }

    const confirmSave = (
        content?: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'save',
            title: '确认保存',
            content: content || '确定要保存当前更改吗？',
            onOk: onConfirm
        })
    }

    const confirmExport = (
        content?: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'export',
            title: '确认导出',
            content: content || '确定要导出数据吗？',
            onOk: onConfirm
        })
    }

    const confirmReset = (
        content?: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'reset',
            title: '确认重置',
            content: content || '重置将清除所有当前设置，确定要继续吗？',
            onOk: onConfirm
        })
    }

    const confirmCancel = (
        content?: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'cancel',
            title: '确认取消',
            content: content || '确定要取消当前操作吗？未保存的更改将丢失。',
            onOk: onConfirm
        })
    }

    const showWarning = (
        content: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'warning',
            title: '警告',
            content,
            onOk: onConfirm
        })
    }

    const showInfo = (
        content: string,
        onConfirm?: () => void | Promise<void>
    ): Promise<boolean> => {
        return showConfirmation({
            type: 'info',
            title: '信息',
            content,
            onOk: onConfirm
        })
    }

    return {
        showConfirmation,
        confirmDelete,
        confirmSave,
        confirmExport,
        confirmReset,
        confirmCancel,
        showWarning,
        showInfo
    }
}

// 批量操作确认对话框
interface BatchOperationConfirmProps {
    visible: boolean
    operation: string
    itemCount: number
    itemType: string
    onConfirm: () => void | Promise<void>
    onCancel: () => void
}

export const BatchOperationConfirm: React.FC<BatchOperationConfirmProps> = ({
    visible,
    operation,
    itemCount,
    itemType,
    onConfirm,
    onCancel
}) => {
    const [loading, setLoading] = React.useState(false)

    const handleConfirm = async () => {
        setLoading(true)
        try {
            await onConfirm()
        } finally {
            setLoading(false)
        }
    }

    return (
        <Modal
            title={
                <div className="flex items-center space-x-2">
                    <ExclamationCircleOutlined className="text-orange-500" />
                    <span>批量{operation}确认</span>
                </div>
            }
            open={visible}
            onOk={handleConfirm}
            onCancel={onCancel}
            okText={`${operation} ${itemCount} 个${itemType}`}
            cancelText="取消"
            okType="danger"
            confirmLoading={loading}
            width={450}
            centered
        >
            <div className="py-4">
                <Alert
                    message={`即将${operation} ${itemCount} 个${itemType}`}
                    description={`此操作将影响 ${itemCount} 个${itemType}，请确认是否继续。`}
                    type="warning"
                    showIcon
                    className="mb-4"
                />
                <p className="text-gray-600 text-sm">
                    注意：批量操作可能需要一些时间完成，请耐心等待。
                </p>
            </div>
        </Modal>
    )
}

export default {
    ConfirmationDialog,
    ConfirmationManager,
    BatchOperationConfirm,
    useConfirmation
}